package com.canglion.ragflow.auth;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.canglion.ragflow.config.RAGFlowConfig;
import com.canglion.ragflow.exception.RAGFlowException;
import lombok.Getter;

import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * rundreams.blog.csdn.net
 *
 * @Time:2025/9/4
 * @Author: Zihao Zhang
 * @description:
 */

public class AuthManager {

    private final RAGFlowConfig config;
    @Getter
    private volatile String accessToken;

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public AuthManager(RAGFlowConfig config) {
        this.config = config;
    }

    public synchronized void login() {

        // Header参数
        HashMap<String, String> headers = new HashMap<>();
        headers.put("authorization", accessToken);

        // 发送GET请求
        HttpResponse response = HttpRequest.get(config.getBaseUrl() + "/v1/user/info")
                .addHeaders(headers)
                .execute();
        // 获取响应内容
        String body = response.body();
        // 解析JSON响应体
        HashMap<String, Object> resultMap = JSONUtil.toBean(body, HashMap.class);
        // 判断code是否为401
        boolean isUnauthorized = "401".equals(resultMap.get("code").toString());

        if (isUnauthorized) {
            // 构造请求参数
            JSONObject jsonParam = JSONUtil.createObj()
                    .put("email", config.getUsername())
                    .put("password", config.getPassword());

            // 发送POST请求
            HttpResponse response2 = HttpRequest.post(config.getBaseUrl() + "/v1/user/login")
                    .header("Content-Type", "application/json")
                    .body(jsonParam.toString())
                    .execute();
            // 获取指定的响应头字段
            String authorizationHeader = response2.header("Authorization");
            if (StrUtil.isEmpty(authorizationHeader)) {
                throw new RAGFlowException("RAGFlow获取授权信息失败");
            }
            accessToken = authorizationHeader;
        }

        if (this.accessToken == null || this.accessToken.isEmpty()) {
            throw new RAGFlowException("Token not found in login response");
        }
    }

    public String getAccessToken() {
        if (accessToken == null) {
            login();
        }
        return accessToken;
    }

    public void startAutoRefresh() {
        scheduler.scheduleAtFixedRate(this::login,
                config.getTokenRefreshInterval(),
                config.getTokenRefreshInterval(),
                TimeUnit.MILLISECONDS);
    }

    public void shutdown() {
        scheduler.shutdown();
    }
}
